package today.rocky.elegantcoding.advice;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import today.rocky.elegantcoding.common.CommonResult;
import today.rocky.elegantcoding.common.ResultCode;
import today.rocky.elegantcoding.exception.BusinessException;

import java.io.FileNotFoundException;

/**
 * @author Rocky
 * @version 1.0
 * @date 2020/5/19 12:01
 * @Description 统一异常处理
 */
@Slf4j
@RestControllerAdvice
public class AdviceController {

	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(value = Exception.class)
	public CommonResult exceptionHander(Exception e){
		StackTraceElement ste = e.getStackTrace()[0];
		log.error(ste.getClassName()+"%"+ste.getMethodName()+"--"+e.getMessage());
		if (e instanceof InterruptedException){
			return CommonResult.failed("中断异常");
		}
		if(e instanceof FileNotFoundException){
			return CommonResult.failed("文件不存在");
		}
		if(e instanceof MethodArgumentNotValidException){
			MethodArgumentNotValidException ex = (MethodArgumentNotValidException)e;
			return 	CommonResult.failed(ResultCode.VALIDATE_FAILED,
					"参数校验错误:"+ex.getBindingResult().getFieldError().getDefaultMessage());
		}
		if(e instanceof BusinessException){
			return CommonResult.failed(e.getMessage());
		}
		return CommonResult.failed();
	}
}
